package com.newsmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newsmanagement.domain.pojo.Admin;
import com.newsmanagement.domain.pojo.NodeInfo;
import com.newsmanagement.exceptions.UsernamePasswordException;
import com.newsmanagement.service.AdminService;
import com.newsmanagement.mapper.AdminMapper;
import com.newsmanagement.utils.JwtUtil;
import com.newsmanagement.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* @author adim
* @description 针对表【admin(系统管理员表)】的数据库操作Service实现
* @createDate 2025-10-09 14:17:47
*/
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 管理员登录
     * @param admin
     * @return
     */
    @Override
    public String adminLogin(Admin  admin) {
        //查找这个节点账号是否存在
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(admin.getAdminName() != null, Admin::getAdminName, admin.getAdminName() );
        Admin adminInfo = adminMapper.selectOne(queryWrapper);

        //判断用户是否存在
        if (adminInfo == null) {
            throw new UsernamePasswordException("该节点企业不存在");
        }
        //判断密码是否正确  u对象中的password是密文
        if (Md5Util.getMD5String(admin.getAdminPassword()).equals(adminInfo.getAdminPassword())) {
            //登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", adminInfo.getAdminId());
            claims.put("username", adminInfo.getAdminName());
            String token = JwtUtil.genToken(claims);
            //把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            return token;
        }
        return null;
    }
}




